<template>
    <div class="layout">
        <div class="page-top-bar">
            <div class="container">
                <div class="top-bar-content">
                    <div class="top-bar-left">
                        <el-icon>
                            <Sunny />
                        </el-icon>
                        <span>欢迎来到水土TU博客</span>
                    </div>
                    <div class="top-bar-right">
                        <router-link to="/concat" class="top-link">
                            <el-icon>
                                <Message />
                            </el-icon>
                            <span>联系作者</span>
                        </router-link>
                        <template v-if="!isLoggedIn">
                            <router-link to="/login" class="top-link">
                                <el-icon>
                                    <User />
                                </el-icon>
                                <span>登录</span>
                            </router-link>
                            <router-link to="/register" class="top-link">
                                <el-icon>
                                    <UserFilled />
                                </el-icon>
                                <span>注册</span>
                            </router-link>
                        </template>
                        <template v-else>
                            <router-link to="/user" class="top-link user-info-link">
                                <el-avatar :size="24" :src="userAvatar" class="user-avatar">
                                    <el-icon>
                                        <User />
                                    </el-icon>
                                </el-avatar>
                                <span>{{ username || '用户' }}</span>
                            </router-link>
                        </template>
                    </div>
                </div>
            </div>
        </div>

        <div class="page-navbar">
            <div class="container">
                <div class="navbar-content">
                    <div class="navbar-brand">
                        <router-link to="/home" class="logo-link">
                            <div class="logo-icon">
                                <el-icon>
                                    <Reading />
                                </el-icon>
                            </div>
                            <span class="logo-text">水土TU</span>
                        </router-link>
                    </div>

                    <div class="navbar-menu" :class="{ 'menu-open': isShow }">
                        <router-link to="/home" class="nav-link" active-class="active" @click="isShow = false">
                            <el-icon>
                                <HomeFilled />
                            </el-icon>
                            <span>首页</span>
                        </router-link>
                        <router-link to="/discover" class="nav-link" active-class="active" @click="isShow = false">
                            <el-icon>
                                <Search />
                            </el-icon>
                            <span>发现</span>
                        </router-link>
                        <router-link to="/message" class="nav-link" active-class="active" @click="isShow = false">
                            <el-icon>
                                <ChatDotRound />
                            </el-icon>
                            <span>留言墙</span>
                        </router-link>
                        <router-link to="/user" class="nav-link" active-class="active" @click="isShow = false">
                            <el-icon>
                                <User />
                            </el-icon>
                            <span>个人中心</span>
                        </router-link>
                    </div>

                    <div class="navbar-search">
                        <el-input placeholder="搜索文章..." @focus="jumpTo" class="search-input" :prefix-icon="Search" />
                    </div>

                    <div class="navbar-toggle" @click="showMenuFn">
                        <el-icon>
                            <Menu />
                        </el-icon>
                    </div>
                </div>
            </div>
        </div>

        <div class="page-content">
            <router-view v-slot="{ Component }">
                <transition enter-active-class="animate__animated animate__fadeIn" mode="out-in">
                    <component :is="Component" />
                </transition>
            </router-view>
        </div>

        <div class="page-footer" v-if="!showToggleButton">
            <div class="container">
                <div class="footer-content">
                    <div class="footer-left">
                        <div class="footer-logo">
                            <el-icon>
                                <Reading />
                            </el-icon>
                            <span>水土TU</span>
                        </div>
                        <p class="footer-desc">分享生活，记录成长</p>
                    </div>
                    <div class="footer-links">
                        <div class="link-group">
                            <h4>快速链接</h4>
                            <router-link to="/home">首页</router-link>
                            <router-link to="/discover">发现</router-link>
                            <router-link to="/message">留言墙</router-link>
                        </div>
                        <div class="link-group">
                            <h4>关于我们</h4>
                            <router-link to="/concat">联系作者</router-link>
                        </div>
                        <div class="link-group">
                            <h4>用户中心</h4>
                            <template v-if="!isLoggedIn">
                                <router-link to="/login">登录</router-link>
                                <router-link to="/register">注册</router-link>
                            </template>
                            <template v-else>
                                <router-link to="/user">个人中心</router-link>
                            </template>
                        </div>
                    </div>
                </div>

            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { getCurrentUserDetail, host } from '@/api'
import {
    Search,
    Menu,
    HomeFilled,
    Reading,
    User,
    UserFilled,
    Message,
    ChatDotRound,
    Sunny
} from '@element-plus/icons-vue'

const router = useRouter()
const isShow = ref<boolean>(false)
const username = ref<string>('')
const userAvatar = ref<string>('')
const showToggleButton = ref<boolean>(false)

const isLoggedIn = computed(() => {
    const token = localStorage.getItem('AUTO_TOKEN')
    return !!token
})

const getFullImageUrl = (imgUrl: string) => {
    if (!imgUrl) return ''
    if (imgUrl.startsWith('http://') || imgUrl.startsWith('https://')) {
        return imgUrl
    }
    const urlPath = imgUrl.startsWith('/') ? imgUrl : '/' + imgUrl
    return host + urlPath
}

const updateUserInfo = async () => {
    const token = localStorage.getItem('AUTO_TOKEN')
    const storedUsername = localStorage.getItem('USERNAME')
    const storedAvatar = localStorage.getItem('USER_AVATAR')

    if (token) {
        username.value = storedUsername || '用户'
        if (storedAvatar) {
            userAvatar.value = getFullImageUrl(storedAvatar)
        } else {
            userAvatar.value = ''
        }

        try {
            const resData = await getCurrentUserDetail()
            if (resData && resData.code === 200 && resData.data) {
                const userData = resData.data
                if (userData.username) {
                    username.value = userData.username
                    localStorage.setItem("USERNAME", userData.username)
                }
                if (userData.imgUrl) {
                    userAvatar.value = getFullImageUrl(userData.imgUrl)
                    localStorage.setItem("USER_AVATAR", userData.imgUrl)
                } else {
                    userAvatar.value = ''
                    localStorage.removeItem("USER_AVATAR")
                }
            }
        } catch (error) {
            console.error('获取用户信息失败:', error)
        }
    } else {
        username.value = ''
        userAvatar.value = ''
    }
}

const handleStorageChange = (e: StorageEvent | Event) => {
    if (e instanceof StorageEvent) {
        if (e.key === 'AUTO_TOKEN' || e.key === 'USERNAME' || e.key === 'USER_AVATAR') {
            updateUserInfo()
        }
    } else {
        updateUserInfo()
    }
}

const showMenuFn = () => {
    isShow.value = !isShow.value
}

const jumpTo = () => {
    router.push({ path: "/search" })
}

const checkScreenSize = () => {
    showToggleButton.value = window.innerWidth <= 992
}

let checkInterval: number | null = null

onMounted(() => {
    updateUserInfo()
    checkScreenSize()
    window.addEventListener('storage', handleStorageChange)
    window.addEventListener('resize', checkScreenSize)
    router.afterEach(() => {
        updateUserInfo()
    })
    checkInterval = setInterval(() => {
        const token = localStorage.getItem('AUTO_TOKEN')
        if (!token && isLoggedIn.value) {
            updateUserInfo()
        }
    }, 1000)
})

onUnmounted(() => {
    window.removeEventListener('storage', handleStorageChange)
    window.removeEventListener('resize', checkScreenSize)
    if (checkInterval) {
        clearInterval(checkInterval)
    }
})
</script>


<style lang="less" scoped>
@import "./assets/varable.less";

.layout {
    font-family: '吉页大字体简', -apple-system, BlinkMacSystemFont, 'Segoe UI', Arial, sans-serif;
    min-height: 100vh;
    display: flex;
    flex-direction: column;
    background: @bg-primary;
}

.page-top-bar {
    background: linear-gradient(135deg, @primary-color 0%, @primary-dark 100%);
    color: @text-white;
    padding: 8px 0;
    font-size: 14px;
    box-shadow: @shadow-sm;

    .top-bar-content {
        display: flex;
        justify-content: space-between;
        align-items: center;

        .top-bar-left {
            display: flex;
            align-items: center;
            gap: 8px;

            .el-icon {
                font-size: 18px;
            }
        }

        .top-bar-right {
            display: flex;
            gap: 20px;

            .top-link {
                display: flex;
                align-items: center;
                gap: 5px;
                color: @text-white;
                text-decoration: none;
                transition: all 0.3s;
                opacity: 0.9;

                &:hover {
                    opacity: 1;
                    transform: translateY(-1px);
                }

                .el-icon {
                    font-size: 16px;
                }

                &.user-info-link {
                    gap: 8px;
                    padding: 4px 12px;
                    border-radius: 20px;
                    background: rgba(255, 255, 255, 0.1);
                    backdrop-filter: blur(10px);

                    &:hover {
                        background: rgba(255, 255, 255, 0.2);
                    }

                    .user-avatar {
                        flex-shrink: 0;
                    }
                }
            }
        }
    }
}

.page-navbar {
    background: @bg-white;
    box-shadow: @shadow-md;
    position: sticky;
    top: 0;
    z-index: 100;
    padding: 0;

    .navbar-content {
        display: flex;
        align-items: center;
        justify-content: space-between;
        height: 70px;
        gap: 20px;
    }

    .navbar-brand {
        .logo-link {
            display: flex;
            align-items: center;
            gap: 12px;
            text-decoration: none;
            color: @text-primary;
            transition: all 0.3s;

            &:hover {
                transform: scale(1.05);

                .logo-icon {
                    background: linear-gradient(135deg, @primary-dark 0%, @primary-color 100%);
                }
            }

            .logo-icon {
                width: 45px;
                height: 45px;
                background: linear-gradient(135deg, @primary-color 0%, @primary-dark 100%);
                border-radius: 12px;
                display: flex;
                align-items: center;
                justify-content: center;
                color: @text-white;
                box-shadow: @shadow-sm;
                transition: all 0.3s;

                .el-icon {
                    font-size: 24px;
                }
            }

            .logo-text {
                font-size: 24px;
                font-weight: bold;
                background: linear-gradient(135deg, @primary-color 0%, @primary-dark 100%);
                -webkit-background-clip: text;
                -webkit-text-fill-color: transparent;
                background-clip: text;
            }
        }
    }

    .navbar-menu {
        display: flex;
        gap: 5px;
        flex: 1;
        justify-content: center;

        .nav-link {
            display: flex;
            align-items: center;
            gap: 6px;
            padding: 10px 20px;
            color: @text-secondary;
            text-decoration: none;
            border-radius: 8px;
            transition: all 0.3s;
            font-weight: 500;

            .el-icon {
                font-size: 18px;
            }

            &:hover {
                color: @primary-color;
                background: @primary-lighter;
            }

            &.active {
                color: @primary-color;
                background: @primary-lighter;
                font-weight: 600;
            }
        }
    }

    .navbar-search {
        width: 240px;

        .search-input {
            border-radius: 20px;

            :deep(.el-input__wrapper) {
                border-radius: 20px;
                box-shadow: 0 0 0 1px @border-color inset;
                transition: all 0.3s;

                &:hover {
                    box-shadow: 0 0 0 1px @primary-light inset;
                }
            }

            :deep(.el-input__wrapper.is-focus) {
                box-shadow: 0 0 0 1px @primary-color inset !important;
            }
        }
    }

    .navbar-toggle {
        display: none;
        width: 40px;
        height: 40px;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        border-radius: 8px;
        transition: all 0.3s;
        color: @text-secondary;

        &:hover {
            background: @primary-lighter;
            color: @primary-color;
        }

        .el-icon {
            font-size: 24px;
        }
    }
}

.page-content {
    flex: 1;
    padding: 30px 0;
    min-height: calc(100vh - 380px);
}

.page-footer {
    background: linear-gradient(180deg, @bg-white 0%, @primary-lighter 100%);
    border-top: 1px solid @border-light;
    padding: 50px 0 20px;
    margin-top: 50px;

    .footer-content {
        display: flex;
        align-items: center;
        justify-content: center;
        padding-bottom: 40px;
        border-bottom: 1px solid @border-light;
        gap: 80px;
    }

    .footer-left {


        .footer-logo {
            display: flex;
            align-items: center;
            gap: 10px;
            font-size: 24px;
            font-weight: bold;
            color: @primary-color;
            margin-bottom: 15px;

            .el-icon {
                font-size: 32px;
            }
        }

        .footer-desc {
            color: @text-secondary;
            margin: 0;
        }
    }

    .footer-links {
        display: flex;
        justify-content: center;
        gap: 80px;

        .link-group {
            h4 {
                font-size: 16px;
                font-weight: 600;
                color: @text-primary;
                margin-bottom: 15px;
            }

            a {
                display: block;
                color: @text-secondary;
                text-decoration: none;
                margin-bottom: 10px;
                transition: all 0.3s;

                &:hover {
                    color: @primary-color;
                    transform: translateX(5px);
                }
            }
        }
    }

}

@media (max-width: 992px) {
    .page-top-bar {
        .top-bar-content {
            .top-bar-left span {
                display: none;
            }
        }
    }

    .page-navbar {
        .navbar-menu {
            position: fixed;
            top: 70px;
            left: 0;
            right: 0;
            flex-direction: column;
            background: @bg-white;
            padding: 20px;
            gap: 10px;
            box-shadow: @shadow-lg;
            transform: translateX(-100%);
            transition: transform 0.3s;
            z-index: 99;
            max-height: calc(100vh - 70px);
            overflow-y: auto;

            &.menu-open {
                transform: translateX(0);
            }

            .nav-link {
                width: 100%;
                justify-content: flex-start;
                padding: 15px 20px;
            }
        }

        .navbar-search {
            display: none;
        }

        .navbar-toggle {
            display: flex;
        }
    }

    .page-footer {
        .footer-content {
            flex-direction: column;
            gap: 40px;
        }

        .footer-links {
            gap: 40px;
        }
    }
}

@media (max-width: 768px) {
    .page-top-bar {
        display: none;
    }

    .page-navbar {
        .navbar-content {
            height: 60px;
        }

        .navbar-brand {
            .logo-link {
                gap: 8px;

                .logo-icon {
                    width: 40px;
                    height: 40px;

                    .el-icon {
                        font-size: 20px;
                    }
                }

                .logo-text {
                    font-size: 20px;
                }
            }
        }
    }

    .page-content {
        padding: 20px 0;
    }

    .page-footer {
        padding: 30px 0 15px;

        .footer-links {
            flex-direction: column;
            gap: 30px;
        }
    }
}

@media (max-width: 576px) {
    .page-navbar {
        .navbar-menu {
            top: 60px;
        }
    }
}
</style>